<?php

# http://projects:8081/cdapp-hole-api/api/load_post.php

include_once '_portal.php';

$page = isset($post->page) ? $post->page : 1;
$type = isset($post->type) ? $post->type : 'all';
$office = isset($post->office) ? $post->office : '';
$user = isset($post->user) ? $post->user : null;

$status = '(1)';
$public = '(0,1)';
$mentioned = null;

// types: all, public, private, mine, mentioned, pending

switch ($type) {
case 'all':
  $status = '(1)';
  $public = '(0,1)';
  break;
case 'public':
  $status = '(1)';
  $public = '(1)';
  break;
case 'private':
  $status = '(1)';
  $public = '(0)';
  break;
case 'mine':
  $status = '(0,1)';
  $public = '(0,1)';
  break;
case 'mentioned':
  $status = '(1)';
  $public = '(0,1)';
  break;
case 'pending':
  $status = '(0)';
  $public = '(0,1)';
  break;
default:
  $status = '(1)';
  $public = '(0,1)';
  break;
}

$conditions = "`forward` = -1 AND `office`={$office} AND `status` IN {$status} AND `public` IN {$public}";

if ($type == 'mine' && $user) {
  $user_number = $user->number;
  $conditions .= " AND `user`->'$.number'={$user_number}";
}

if (($type == 'mentioned' || $type == 'private') && $user) {
  $user_number = $user->number;
  $conditions .= " AND JSON_CONTAINS(mentioned,JSON_Array({$user_number})";
}

// if ($type == 'mine' && (!$user || !$user->holeLevel || $user->holeLevel == 0)) {
//   $conditions .= " AND false";
// }

$sql_count = "SELECT COUNT(*) FROM `3hole_posts` WHERE {$conditions}";
$result_count = exec_sql($sql_count);

$offset = $page * 20;
$limit = 20;

$sql = "SELECT * FROM `3hole_posts` WHERE {$conditions} ORDER BY `updated` DESC LIMIT {$offset},{$limit}";

$result = exec_sql($sql);

$success = false;

$sql_replies = [];

if ($result) {
  $success = true;
  $result = query_parse($result);
  for ($i = 0; $i < count($result); $i++) {
    $result[$i]["replies"] = [];
    $forward = $result[$i]["code"];
    $sql_reply = "SELECT * FROM `3hole_posts` WHERE `forward` = {$forward} ORDER BY `code` DESC";
    $sql_replies[] = $sql_reply;
    $result_reply = exec_sql($sql_reply);
    if ($result_reply) {
      $result[$i]["replies"] = query_parse($result_reply);
    }
  }
}

output([
  'status' => $success,
  'count' => $result_count[0]['COUNT(*)'],
  'result' => $result ? $result : [],
  'sql' => $sql,
  'sql_replies' => $sql_replies,
  'sql_count' => $sql_count,
  'post' => $post,
]);